<template>
    <div class="h100">
        <!-- 卡片 -->
        <el-card class="box-card">
            <!-- 登录表单 -->
            <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="40px"
                class="demo-ruleForm">
                <el-form-item label="账号" prop="userName">
                    <el-input v-model="ruleForm.userName" type="text" autocomplete="off" />
                </el-form-item>
                <el-form-item label="密码" prop="passWord">
                    <el-input v-model="ruleForm.passWord" type="password" autocomplete="off" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm(ruleFormRef)" style="width: 100%;">登录</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { userLogin } from '../api/user'
import { useRouter } from "vue-router"

const router = useRouter()
const ruleFormRef = ref<FormInstance>()

const username = (_rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入账号'))
    } else {
        callback()
    }
}
const password = (_rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入密码'))
    } else {
        callback()
    }
}

const ruleForm = reactive({
    userName: '',
    passWord: '',
})

const rules = reactive<FormRules<typeof ruleForm>>({
    userName: [{ validator: username, trigger: 'blur' }],
    passWord: [{ validator: password, trigger: 'blur' }],
})

const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            userLogin({ ...ruleForm }).then(res => {
                // console.log(res)
                // 登录成功，存入本地token
                if (res.data.code === 0) {
                    localStorage.setItem('token', res.data.token)
                    localStorage.setItem('refreshToken', res.data.refreshToken)
                    setTimeout(() => {
                        router.push('/home')
                    }, 1500);

                }
            })
        } else {
            return false
        }
    })
}


</script>

<style scoped>
.h100 {
    height: 100%;
    background-color: skyblue;
    position: relative;
}

.box-card {
    width: 480px;
    position: absolute;
    top: 20%;
    left: 50%;
}
</style>